

#import "MusicViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "MusicModel.h"
#import "MusicSharedData.h"
@interface MusicViewController ()<UITableViewDataSource, UITableViewDelegate,AVAudioPlayerDelegate>
{
    AVAudioPlayer *audioPlayer;
    BOOL isPlay; // 用来记录是否正在播放
}
@property(nonatomic, strong)NSMutableArray *timeArray; // 时间数组
@property(nonatomic, strong)NSMutableDictionary *lrcDictionary; // 歌词字典
@end

@implementation MusicViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.timeArray = [NSMutableArray array];
        self.lrcDictionary = [NSMutableDictionary dictionary];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    MusicModel *model = [MusicSharedData sharedInstance].musicArray[self.playIndex];

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:model.musicName ofType:model.musicType]] error:nil];


    self.volumeSlider.minimumValue = 0;
    self.volumeSlider.maximumValue = 1;
    
    // 初始音量
    audioPlayer.volume = 0;
    self.volumeSlider.value = audioPlayer.volume;
    // 设置音量的按钮颜色
    [self.volumeSlider setThumbImage:[UIImage imageNamed:@"soundSlider.png"] forState:UIControlStateNormal];
    [self.volumeSlider setThumbImage:[UIImage imageNamed:@"soundSlider.png"] forState:UIControlStateHighlighted];

    // 设置进度的按钮颜色
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"sliderThumb_small.png"] forState:UIControlStateNormal];
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"sliderThumb_small.png"] forState:UIControlStateHighlighted];
    // 获取歌词
    [self getLyric];


    // 设置歌词的代理
    self.lyricTableView.delegate = self;
    self.lyricTableView.dataSource = self;




    // 设置检控,每隔一秒刷新一次
    [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(showTime) userInfo:nil repeats:YES];
}


#pragma mark 0.1秒一次更新 播放时间 播放进度条 歌词 歌曲 自动播放下一首
- (void)showTime {
    //动态更新进度条时间
    if ((int)audioPlayer.currentTime % 60 < 10) {
        self.StratTimeLable.text = [NSString stringWithFormat:@"%d:0%d",(int)audioPlayer.currentTime / 60, (int)audioPlayer.currentTime % 60];
    } else {
        self.StratTimeLable.text = [NSString stringWithFormat:@"%d:%d",(int)audioPlayer.currentTime / 60, (int)audioPlayer.currentTime % 60];
    }
    //
    if ((int)audioPlayer.duration % 60 < 10) {
        self.endtimeLable.text = [NSString stringWithFormat:@"%d:0%d",(int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60];
    } else {
        self.endtimeLable.text = [NSString stringWithFormat:@"%d:%d",(int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60];
    }
    self.progressSlider.value = audioPlayer.currentTime / audioPlayer.duration;

    [self displaySondWord:audioPlayer.currentTime];//调用歌词函数
//
//    //如果播放完，调用自动播放下一首
    if (self.progressSlider.value > 0.999) {
        [self autoPlay];
    }
//


}

#pragma mark 自动进入下一首
- (void)autoPlay {
    //判断是否允许循环播放
        if (self.playIndex == [MusicSharedData sharedInstance].musicArray.count - 1) {
            self.playIndex = -1;
        }
        self.playIndex ++;

        [self updatePlayerSetting];
}


#pragma mark 得到歌词
-(void)getLyric
{

    MusicModel *model = [MusicSharedData sharedInstance].musicArray[self.playIndex];
    NSString *LRCPath = [[NSBundle mainBundle] pathForResource:model.musicName ofType:@"lrc"];
    NSString *lrcUTF8 = [NSString stringWithContentsOfFile:LRCPath encoding:NSUTF8StringEncoding error:nil];
    NSArray *array = [lrcUTF8 componentsSeparatedByString:@"\n"];
    for (int i = 0; i < array.count; i ++) {
        NSString *linStr = [array objectAtIndex:i];
         NSArray *lineArray = [linStr componentsSeparatedByString:@"]"];
        if ([lineArray[0] length] > 8) {
            NSString *str1 = [linStr substringWithRange:NSMakeRange(3, 1)];//:
            NSString *str2 = [linStr substringWithRange:NSMakeRange(6, 1)];//.
            if ([str1 isEqualToString:@":"] && [str2 isEqualToString:@"."]) {
                NSString *lrcStr = [lineArray objectAtIndex:1];//歌词
                NSString *timeStr = [lineArray[0] substringWithRange:NSMakeRange(1, 5)];//时间
                [self.timeArray addObject:timeStr];
                [self.lrcDictionary setObject:lrcStr forKey:timeStr];
                
            }
        }

    }
}

// 循环按钮点击
- (IBAction)circleButtonDidClicked:(id)sender {


}


- (IBAction)backButtonDidClicked:(id)sender {

    if (self.playIndex == 0) {
        self.playIndex = [MusicSharedData sharedInstance].musicArray.count;
    }
    self.playIndex --;
    [self updatePlayerSetting];

}


- (IBAction)playButtonDidClicked:(id)sender {

    if (!isPlay) {
        [audioPlayer play];
        [self.playButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        isPlay = YES;
    }else{
        [audioPlayer pause];
        [self.playButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        isPlay = NO;

    }
}

- (IBAction)speedButtonDidClicked:(id)sender {

    if (self.playIndex == [MusicSharedData sharedInstance].musicArray.count - 1) {
        self.playIndex = -1;
    }
    self.playIndex ++;
    [self updatePlayerSetting];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded] && self.view.window == nil) {
        self.view = nil;
    }
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.timeArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellIdentifier = @"LRCCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;//该表格选中后没有颜色
    cell.backgroundColor = [UIColor clearColor];


    cell.textLabel.text = self.lrcDictionary[self.timeArray[indexPath.row]];
    cell.textLabel.textColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    cell.textLabel.font = [UIFont systemFontOfSize:13];

    cell.textLabel.backgroundColor = [UIColor clearColor];
//        cell.textLabel.textColor = [UIColor blackColor];

    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    return cell;

}


#pragma mark 动态显示歌词
- (void)displaySondWord:(NSUInteger)time {
    //    NSLog(@"time = %u",time);
    for (int i = 0; i < [self.timeArray count]; i++) {

        

        if (i == [self.timeArray count]-1) {
            //求最后一句歌词的时间点
            NSArray *array1 = [self.timeArray[self.timeArray.count-1] componentsSeparatedByString:@":"];
            NSUInteger currentTime1 = [array1[0] intValue] * 60 + [array1[1] intValue];

            if (time > currentTime1) {
                [self updateLrcTableView:i];
                break;
            }
        } else {
            //求出第一句的时间点，在第一句显示前的时间内一直加载第一句
            NSArray *array2 = [self.timeArray[0] componentsSeparatedByString:@":"];
            NSUInteger currentTime2 = [array2[0] intValue] * 60 + [array2[1] intValue];
            if (time < currentTime2) {
                [self updateLrcTableView:0];
                //                NSLog(@"马上到第一句");
                break;
            }
            //求出下一步的歌词时间点，然后计算区间
            //第i个
            NSArray *array = [self.timeArray[i] componentsSeparatedByString:@":"];//把时间转换成秒
            NSUInteger currentTime = [array[0] intValue] * 60 + [array[1] intValue];
            
            //第i + 1个
            NSArray *array3 = [self.timeArray[i+1] componentsSeparatedByString:@":"];
            NSUInteger currentTime3 = [array3[0] intValue] * 60 + [array3[1] intValue];
            if (time >= currentTime && time <= currentTime3) {
                [self updateLrcTableView:i];
                break;
            }

        }
    }
}

#pragma mark 动态更新歌词表歌词
- (void)updateLrcTableView:(NSUInteger)lineNumber {

    [self.lyricTableView reloadData];
    //使被选中的行移到中间
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lineNumber inSection:0];
    //设置当前歌词的cell颜色
    UITableViewCell *cell = [self.lyricTableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor greenColor];
    
    //tableView居中循环
    [self.lyricTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}


#pragma mark 更新播放
//更新播放器设置
- (void)updatePlayerSetting {
    //更新播放按钮状态
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    isPlay = YES;

    MusicModel *model = [MusicSharedData sharedInstance].musicArray[self.playIndex];

    //更新曲目
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:model.musicName ofType:@"mp3"]] error:nil];
//    currentMusic = musicArray[musicArrayNumber];
    //更新音量
    audioPlayer.volume = self.volumeSlider.value;
    //重新载入歌词词典
    self.timeArray = [[NSMutableArray alloc] initWithCapacity:10];
    self.lrcDictionary = [[NSMutableDictionary alloc] initWithCapacity:10];
    [self getLyric];

    [audioPlayer play];
}
// 音量

- (IBAction)volumChangeAction:(id)sender {
    audioPlayer.volume = self.volumeSlider.value;

}

- (IBAction)progressChangeAction:(id)sender {
    audioPlayer.currentTime = self.progressSlider.value * audioPlayer.duration;
}



@end
